<template>
  <div class="reports-container">
    <!-- 头部 -->
    <div class="reports-header">
      <h1 class="page-title">数据报表</h1>
      <p class="page-subtitle">查看系统数据统计和分析报表</p>
    </div>

    <div class="reports-content">
      <!-- 过滤区 -->
      <el-card shadow="always" class="mb-16">
        <el-form :inline="true" label-width="80px" class="filter-form">
          <el-form-item label="报表类型">
            <el-select
              v-model="selectedReportType"
              @change="loadReport"
              placeholder="选择报表类型"
              style="width: 180px"
            >
              <el-option label="销售报表" value="sales" />
              <el-option label="用户报表" value="users" />
              <el-option label="商品报表" value="products" />
              <el-option label="订单报表" value="orders" />
            </el-select>
          </el-form-item>

          <el-form-item label="时间范围">
            <el-select
              v-model="selectedDateRange"
              @change="onDateRangeChange"
              placeholder="选择时间范围"
              style="width: 160px"
            >
              <el-option label="今天" value="today" />
              <el-option label="本周" value="week" />
              <el-option label="本月" value="month" />
              <el-option label="本季度" value="quarter" />
              <el-option label="本年" value="year" />
              <el-option label="自定义" value="custom" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="selectedDateRange === 'custom'" label="日期范围">
            <el-date-picker
              v-model="customRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="onCustomRangeChange"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="generateReport"> 生成报表 </el-button>
            <el-button type="success" plain @click="exportReport" class="ml-8"> 导出 </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 概览卡片 -->
      <el-row :gutter="16" class="mb-16">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card primary" shadow="hover">
            <div class="stat-title">总收入</div>
            <div class="stat-value">¥{{ formatNumber(reportData.totalRevenue) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card success" shadow="hover">
            <div class="stat-title">订单数量</div>
            <div class="stat-value">{{ formatNumber(reportData.totalOrders) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card info" shadow="hover">
            <div class="stat-title">新用户</div>
            <div class="stat-value">{{ formatNumber(reportData.newUsers) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card warning" shadow="hover">
            <div class="stat-title">转化率</div>
            <div class="stat-value">{{ reportData.conversionRate }}%</div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="16" class="mb-16">
        <el-col :xs="24" :md="16">
          <el-card shadow="always">
            <template #header>
              <div class="card-header">
                <span class="card-title">{{ getChartTitle() }}</span>
              </div>
            </template>
            <div class="chart-area">
              <div ref="lineChartRef" class="chart-canvas"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :md="8">
          <el-card shadow="always">
            <template #header>
              <div class="card-header">
                <span class="card-title">数据分布</span>
              </div>
            </template>
            <div class="chart-area">
              <div ref="pieChartRef" class="chart-canvas"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据表格 -->
      <el-card shadow="always">
        <template #header>
          <div class="card-header">
            <span class="card-title">详细数据</span>
          </div>
        </template>
        <div class="table-responsive">
          <el-table :data="tableData" stripe style="width: 100%" empty-text="暂无数据">
            <el-table-column
              v-for="column in tableColumns"
              :key="column.key"
              :prop="column.key"
              :label="column.title"
              min-width="120"
            >
              <template #default="{ row }">
                <span v-if="column.type === 'currency'">¥{{ formatNumber(Number(row[column.key]) || 0) }}</span>
                <span v-else-if="column.type === 'number'">{{ formatNumber(Number(row[column.key]) || 0) }}</span>
                <span v-else-if="column.type === 'percentage'">{{ row[column.key] }}%</span>
                <span v-else>{{ row[column.key] }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";

defineOptions({ name: "ReportsView" });

// 过滤区响应式数据
const selectedReportType = ref("sales");
const selectedDateRange = ref("month");
const customRange = ref<[string, string] | null>(null);

// 兼容原逻辑（若其他处引用）
const customStartDate = ref("");
const customEndDate = ref("");

// 概览数据
const reportData = reactive({
  totalRevenue: 125680.5,
  totalOrders: 1234,
  newUsers: 89,
  conversionRate: 3.2,
});

// 图表源数据
const chartData = ref([
  { label: "1月", value: 12000 },
  { label: "2月", value: 15000 },
  { label: "3月", value: 18000 },
  { label: "4月", value: 22000 },
  { label: "5月", value: 19000 },
  { label: "6月", value: 25000 },
]);

const pieData = ref([
  { label: "电子产品", percentage: 45, color: "#4e73df" },
  { label: "服装鞋帽", percentage: 30, color: "#1cc88a" },
  { label: "图书音像", percentage: 15, color: "#36b9cc" },
  { label: "其他", percentage: 10, color: "#f6c23e" },
]);

// 表格
const tableColumns = ref([
  { key: "date", title: "日期", type: "text" },
  { key: "revenue", title: "收入", type: "currency" },
  { key: "orders", title: "订单数", type: "number" },
  { key: "users", title: "新用户", type: "number" },
  { key: "conversion", title: "转化率", type: "percentage" },
]);

const tableData = ref([
  { date: "2024-01-20", revenue: 5680.5, orders: 45, users: 12, conversion: 3.2 },
  { date: "2024-01-19", revenue: 4320.0, orders: 38, users: 8, conversion: 2.8 },
  { date: "2024-01-18", revenue: 6890.2, orders: 52, users: 15, conversion: 3.8 },
  { date: "2024-01-17", revenue: 3456.8, orders: 29, users: 6, conversion: 2.1 },
  { date: "2024-01-16", revenue: 7234.1, orders: 61, users: 18, conversion: 4.2 },
]);

// 计算属性
const maxChartValue = computed(() => Math.max(...chartData.value.map((item) => item.value)));

// 方法
const formatNumber = (num: number) => num.toLocaleString("zh-CN");

const getChartTitle = () => {
  const typeMap: Record<string, string> = {
    sales: "销售趋势",
    users: "用户增长",
    products: "商品销量",
    orders: "订单统计",
  };
  return typeMap[selectedReportType.value] || "数据趋势";
};

// 原逻辑：载入报表（可接入后端 API）
const loadReport = () => {
  console.log("加载报表:", {
    type: selectedReportType.value,
    dateRange: selectedDateRange.value,
    startDate: customStartDate.value,
    endDate: customEndDate.value,
  });
  updateLineChart();
  updatePieChart();
};

// 触发：生成报表/导出报表
const generateReport = () => {
  console.log("生成报表");
  loadReport();
};
const exportReport = () => {
  console.log("导出报表");
};

// 日期范围联动
const onDateRangeChange = (val: string) => {
  if (val !== "custom") {
    customRange.value = null;
    customStartDate.value = "";
    customEndDate.value = "";
  }
  loadReport();
};
const onCustomRangeChange = (range: [string, string] | null) => {
  if (range) {
    customStartDate.value = range[0];
    customEndDate.value = range[1];
  } else {
    customStartDate.value = "";
    customEndDate.value = "";
  }
  loadReport();
};

// 折线/柱状图
const lineChartRef = ref<HTMLDivElement | null>(null);
let lineChart: echarts.ECharts | null = null;

const initLineChart = () => {
  if (lineChartRef.value) {
    lineChart = echarts.init(lineChartRef.value);
    updateLineChart();
    window.addEventListener("resize", resizeCharts);
  }
};

const updateLineChart = () => {
  if (!lineChart) return;
  const categories = chartData.value.map((d) => d.label);
  const values = chartData.value.map((d) => d.value);

  const isBar = selectedReportType.value === "products" || selectedReportType.value === "orders";
  const series = isBar
    ? [{ type: "bar", data: values, itemStyle: { color: "#4e73df" } }]
    : [{ type: "line", smooth: true, data: values, itemStyle: { color: "#4e73df" } }];

  lineChart.setOption({
    grid: { left: 40, right: 20, top: 40, bottom: 40 },
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: categories, axisLine: { lineStyle: { color: "#c0c4cc" } } },
    yAxis: { type: "value", axisLine: { lineStyle: { color: "#c0c4cc" } } },
    series,
  });
};

// 饼图
const pieChartRef = ref<HTMLDivElement | null>(null);
let pieChart: echarts.ECharts | null = null;

const initPieChart = () => {
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value);
    updatePieChart();
  }
};

const updatePieChart = () => {
  if (!pieChart) return;
  pieChart.setOption({
    tooltip: { trigger: "item" },
    legend: { bottom: 0 },
    series: [
      {
        name: "数据分布",
        type: "pie",
        radius: ["40%", "65%"],
        avoidLabelOverlap: true,
        itemStyle: { borderRadius: 6, borderColor: "#fff", borderWidth: 2 },
        data: pieData.value.map((d) => ({ name: d.label, value: d.percentage, itemStyle: { color: d.color } })),
      },
    ],
  });
};

const resizeCharts = () => {
  lineChart?.resize();
  pieChart?.resize();
};

// 监听报表类型变化，更新表格列与图表
watch(selectedReportType, (newType) => {
  if (newType === "users") {
    tableColumns.value = [
      { key: "date", title: "日期", type: "text" },
      { key: "newUsers", title: "新用户", type: "number" },
      { key: "activeUsers", title: "活跃用户", type: "number" },
      { key: "retention", title: "留存率", type: "percentage" },
    ];
  } else if (newType === "products") {
    tableColumns.value = [
      { key: "product", title: "商品", type: "text" },
      { key: "sales", title: "销量", type: "number" },
      { key: "revenue", title: "收入", type: "currency" },
      { key: "profit", title: "利润", type: "currency" },
    ];
  } else {
    tableColumns.value = [
      { key: "date", title: "日期", type: "text" },
      { key: "revenue", title: "收入", type: "currency" },
      { key: "orders", title: "订单数", type: "number" },
      { key: "users", title: "新用户", type: "number" },
      { key: "conversion", title: "转化率", type: "percentage" },
    ];
  }
  updateLineChart();
});

onMounted(() => {
  initLineChart();
  initPieChart();
  console.log("数据报表页面加载完成");
  loadReport();
});

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  lineChart?.dispose();
  pieChart?.dispose();
  lineChart = null;
  pieChart = null;
});
</script>

<style scoped>
.reports-container {
  padding: 16px 16px 24px;
  background-color: var(--el-bg-color-page);
  min-height: 100vh;
}

.reports-header {
  margin-bottom: 12px;
}
.page-title {
  color: var(--el-text-color-primary);
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}
.page-subtitle {
  color: var(--el-text-color-secondary);
}

.reports-content {
  margin-top: 8px;
}

/* spacing helpers */
.mb-16 {
  margin-bottom: 16px;
}
.ml-8 {
  margin-left: 8px;
}

/* 概览卡片样式 */
.stat-card {
  border-radius: 10px;
  --c: #4e73df;
}
.stat-card.primary {
  --c: #4e73df;
}
.stat-card.success {
  --c: #1cc88a;
}
.stat-card.info {
  --c: #36b9cc;
}
.stat-card.warning {
  --c: #f6c23e;
}
.stat-title {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
.stat-value {
  margin-top: 6px;
  font-size: 22px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}
.stat-card ::v-deep(.el-card__body) {
  border-left: 4px solid var(--c);
}

/* 卡片头 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.card-title {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

/* 图表画布 */
.chart-area {
  width: 100%;
  height: 360px;
}
.chart-canvas {
  width: 100%;
  height: 100%;
}

/* 表格 */
.table-responsive {
  width: 100%;
}
</style>
